/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import servicios.Transaccion;

/**
 *
 * @author Mario Andrés
 */
public abstract class GeneralDAO<T, ID extends Serializable> {

    private EntityManagerFactory emf;
    private Class<? extends T> clase;

    public Class<? extends T> getClase() {
        return clase;
    }

    public void setClase(Class<? extends T> clase) {
        this.clase = clase;
    }

    public boolean create(T entity, Transaccion tx) {
        try {
            tx.getEntityManager().persist(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } 
        return true;
    }

    public List list(Transaccion tx) {
        try {
            List entities = tx.getEntityManager().createQuery(queryList()).getResultList();
            return entities;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean removeAll(Transaccion tx) {
        List l = list(tx);
        try {
            for (int i = 0; i < l.size(); i++) {
                tx.getEntityManager().remove(tx.getEntityManager().merge((T) l.get(i)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public T findForID(Integer ID, Transaccion tx) {
        T entity = null;
        try {
            entity = tx.getEntityManager().find(clase, ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }

    public boolean remove(/*Integer ID*/T entity, Transaccion tx) {
        try {
            //T entity = tx.getEntityManager().find(clase, ID);
            tx.getEntityManager().remove(tx.getEntityManager().merge(entity));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean edit(T entity, Transaccion tx) {
        try {
            tx.getEntityManager().merge(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public EntityManager getEntityManager() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("STAPU");
        }
        return emf.createEntityManager();
    }

    public abstract String queryList();
}
